package utils;

import java.sql.Connection;
import java.util.ArrayList;

import predictors.AttrInfo;
import predictors.AttributeMatcherImpl;

import jobqueue.JobQueueInfo;
import jsonobj.*;
import data.*;

public class ClusterFunctions implements Msg {
	public ClusterFunctions() {}
	
	public Object[] clusterLogin(Connection conn,ClusterLoginInfo cli, String hostname) throws Exception
	{
		if(hostname == null) 
			return new Object[]{new Response(false,ERR),null,null};
		String uname = cli.user;
		String passwd = cli.pass;
		UserInfo ui;
		ClusterInfo ci;
		if((ui = Database.users.get(uname)) == null)
		{
			return new Object[]{new Response(false,USR_ERR),null,null};
		}
		if(!ui.getPasswd().equals(passwd))
		{
			return new Object[]{new Response(false,USR_ERR),null,null};
		}
		ci = Database.clusters.get(uname).get(hostname);
		if( ci == null)
		{
			//info was already in database
			if((ci=Database.getClusterInfo(conn,hostname)) != null)
			{
				Database.clusters.get(uname).put(hostname,ci);
				Database.addClusterToUser(conn, ui, ci);
			}
			else
			{
				//new cluster is registering
				ci = new ClusterInfo(hostname,cli.host);
				if(Database.registerCluster(conn, ui, ci) == SQL_ERR) {
					return new Object[]{new Response(false,SQL_ERR),null,null};
    			}
			}
		}
		//TODO uncomment
		/*else if(ci.isConnected)
		{
			return new Object[]{new Response(false,USR_ERR),null,null};
		}*/
		ui.clusters.put(hostname,ci);
		if(ui.isConnected)
			ui.sendMessage(new Message(CLUSTER_ON,hostname,cli.host));
		ci.local_hostname = cli.host;
		return new Object[]{new Response(true,OK),ui,ci};
	}
}
